# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 工具创建-处理工具错误(使用函数).py
# @Author: dongguangwen
# @Date  : 2025-03-23 22:03
from langchain_core.tools import ToolException, StructuredTool


def get_weather(city: str) -> int:
    """Get weather for the given city."""
    raise ToolException(f"Error: There is no city by the name of {city}.")


def _handle_error(error: ToolException) -> str:
    return f"The following errors occurred during tool execution: `{error.args[0]}`"


get_weather_tool = StructuredTool.from_function(
    func=get_weather,
    handle_tool_error=_handle_error,
)

ret = get_weather_tool.invoke({"city": "foobar"})
print(ret)

"""
The following errors occurred during tool execution: `Error: There is no city by the name of foobar.`
"""